package com.imay.photopicker.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.imay.capturefilter.MagicEngine;
import com.imay.capturefilter.R;
import com.imay.capturefilter.camera.CameraEngine;
import com.imay.capturefilter.camera.utils.CameraUtils;
import com.imay.capturefilter.helper.SavePictureTask;
import com.imay.capturefilter.utils.ICCons;
import com.imay.capturefilter.utils.ICUtils;
import com.imay.capturefilter.utils.MagicFilterTools;
import com.imay.capturefilter.widget.MagicCameraView;
import com.imay.photopicker.ClipActivity;
import com.imay.photopicker.manager.CameraManager;

import java.io.File;

import static com.imay.capturefilter.R.id.glsurfaceview_camera;

/**
 * Created by Administrator on 2017/3/21.
 */

public class CameraFragment extends BaseFragment implements View.OnClickListener{
    private int mFlashMode = 0; //0关，1自动，2开, 3禁用：前置摄像头，

    private MagicEngine mMagicEngine;
    private MagicCameraView mMagicCameraView;
    private ImageView mIvFlash;

    public static CameraFragment newInstance() {
        CameraFragment fragment = new CameraFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.picker_activity_camera;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        MagicEngine.Builder builder = new MagicEngine.Builder();
        mMagicCameraView = $(glsurfaceview_camera);
        mMagicCameraView.setTag("photopicker");
        mMagicEngine = builder.build(mMagicCameraView);
        mMagicCameraView.setOnSurfaceChangedListener(new MagicCameraView.OnSurfaceChangedListener() {
            @Override
            public void sufaceCreate() {
                mMagicEngine.setFilter(MagicFilterTools.types[1]);
            }

            @Override
            public void sufaceChange() {
                mMagicEngine.setFilter(MagicFilterTools.types[1]);
            }
        });

        ImageView mIvFocus = $(R.id.iv_focus);

        CameraManager manager = new CameraManager(getContext(), mMagicCameraView,mIvFocus);

        $(R.id.iv_beauty).setSelected(false);
        $(R.id.iv_switch_camera).setOnClickListener(this);
        $(R.id.iv_btn_take_photo).setOnClickListener(this);
        $(R.id.iv_btn_sys_photo).setOnClickListener(this);
        $(R.id.iv_beauty).setOnClickListener(this);
        $(R.id.iv_close).setOnClickListener(this);
        mIvFlash = $(R.id.iv_flash);
        $(R.id.iv_flash).setOnClickListener(this);

        /**
         * 设置闪光灯图片
         */
        if (!CameraEngine.getCameraBackStatus()) {
            mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos);
        } else {
            mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos_disable);
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_switch_camera) {
            mMagicCameraView.switchCamera();
            if (!CameraEngine.getCameraBackStatus()) {
                mFlashMode = 3;
            } else {
                mFlashMode = 0;
            }
            setViewFlasMode();
        } else if (id == R.id.iv_btn_take_photo) {
            mMagicEngine.setFlashMode(mFlashMode);
            takePhoto();
        } else if (id == R.id.iv_btn_sys_photo) {
            if(cameraCallBackListener != null){
                if(CameraEngine.isOpen){
                    CameraEngine.releaseCamera();
                }
                cameraCallBackListener.callBack();
            }
        } else if (id == R.id.iv_beauty) {
            if (view.isSelected()) {
                mMagicEngine.setFilter(MagicFilterTools.types[1]);
            } else {
                mMagicEngine.setFilter(MagicFilterTools.types[0]);
            }
            view.setSelected(!view.isSelected());
        } else if (id == R.id.iv_close) {
            getActivity().onBackPressed();
        } else if (id == R.id.iv_flash) {
            setFlashMode();
        }
    }

    private void takePhoto() {
        //findViewById(R.id.iv_btn_capture).setEnabled(false);
        final Dialog dialog = ICUtils.createDialog(getActivity(), getString(R.string.IC_img_msg_create));
        dialog.show();
        File imageFile = ICUtils.getOutputMediaFile(getContext());
        if (imageFile != null) {
            mMagicEngine.savePicture(imageFile, new SavePictureTask.OnPictureSaveListener() {
                @Override
                public void onSaved(final String result) {
                    MediaScannerConnection.scanFile(getActivity(),
                            new String[]{result}, null,
                            new MediaScannerConnection.OnScanCompletedListener() {
                                @Override
                                public void onScanCompleted(final String path, final Uri uri) {
                                    // 返回图片路径
                                    dialog.dismiss();
                                    Intent intent = getActivity().getIntent();
                                    intent.putExtra(ICCons.KEY_FILE_PATH, result);
                                    getActivity().setResult(Activity.RESULT_OK, intent);
                                    getActivity().finish();
                                    //ClipActivity.startActivity(getActivity(), ClipActivity.CLIP_REQUEST_CODE_2, result, null);
                                }
                            });

                }
            });
        } else {
            dialog.dismiss();
            Toast.makeText(getActivity(), "保存图片失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void setFlashMode() {
        if (mFlashMode > 1) {
            mFlashMode = 0;
        } else {
            mFlashMode = mFlashMode + 1;
        }
        setViewFlasMode();
    }

    private void setViewFlasMode() {
        if (!CameraEngine.getCameraBackStatus()) {//前置摄像头，不可用
            mMagicEngine.setFlashMode(3);
            mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos);
            mIvFlash.setEnabled(false);
            mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos_disable);
        } else {
            mMagicEngine.setFlashMode(mFlashMode);
            mIvFlash.setEnabled(true);
            if (mFlashMode == 1) {
                mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_auto);
            } else if (mFlashMode == 2) {
                mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_default);
            } else {
                mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos);
            }
        }
    }

    public CameraCallBackListener getCameraCallBackListener() {
        return cameraCallBackListener;
    }

    public void setCameraCallBackListener(CameraCallBackListener cameraCallBackListener) {
        this.cameraCallBackListener = cameraCallBackListener;
    }

    public interface CameraCallBackListener{
        void callBack();
    }

    private CameraCallBackListener cameraCallBackListener;

    @Override
    public void onDestroy() {
        super.onDestroy();
        CameraUtils.release();
        CameraEngine.releaseCamera();
        CameraEngine.onDestroy();
    }
}
